package com.cnebula.uas.sso.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.cnebula.uas.sso.ConfAdmin;
import com.cnebula.uas.sso.service.AuthTokenService;
import com.cnebula.uas.sso.util.Constant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class AuthTokenServiceImpl implements AuthTokenService {

	ObjectMapper mapper = new ObjectMapper();
	CloseableHttpClient httpClient = HttpClients.createDefault();

	@Autowired
	ConfAdmin conf;

	String authTokenURL;

	@PostConstruct
	public void init() {

		StringBuilder authTokenURLBuilder = new StringBuilder();
		authTokenURLBuilder.append("http://").append(conf.okapiHost).append(":").append(conf.okapiPort);
		authTokenURLBuilder.append("/uas/authtoken/token");

		authTokenURL = authTokenURLBuilder.toString();

	}

	@Override
	public ResponseEntity<String> checkToken(String artifact, String okapiTenant) throws Exception {

		CloseableHttpResponse res = null;
		String okapiToken = null;
		try {
			URIBuilder builder = new URIBuilder(authTokenURL);
			builder.setParameter("artifact", artifact);
			HttpGet httpGet = new HttpGet(builder.build());
			httpGet.addHeader(Constant.OKAPI_TENANT_HEADER, okapiTenant);
			httpGet.addHeader(HttpHeaders.CONTENT_ENCODING, "UTF-8");
//			httpGet.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");

			res = httpClient.execute(httpGet);
			HttpEntity entity = res.getEntity();
			int statusCode = res.getStatusLine().getStatusCode();
			String content = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
			if (statusCode != 200) {
				return ResponseEntity.status(statusCode).body(content);
			}

			okapiToken = content;

		} finally {
			if (res != null) {
				res.close();
			}

		}

		return ResponseEntity.ok(okapiToken);
	}

	public static void main(String[] args) throws JsonProcessingException {
		Map<String, String> payload = new HashMap<String, String>();
		payload.put("sub", "username");
		payload.put("userId", "");

		Map<String, Map<String, String>> json = new HashMap<String, Map<String, String>>();
		json.put("payload", payload);

		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(json);

		System.out.println(str);
	}

}
